package com.java.shop.ware.listener;

import com.java.common.to.OrderTo;
import com.java.common.to.mq.StockLockedTo;
import com.java.shop.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

import static com.java.common.constant.MqConstant.ware_ordQueue;

@Service
@RabbitListener(queues = {ware_ordQueue})
public class StockReleaseListenter {
    @Autowired
    WareSkuService wareSkuService;

    /**
     * 监听消息队列，自动解锁库存(被动解锁，即时间到了之后解锁)
     * 1.下单成功，库存锁定成功，接下来业务调用失败，导致订单回滚，之前锁定的库存就要自动解锁
     * 2.订单失败，自身已回滚，查询不到订单号，就直接消费消息
     *
     *
     * @param message
     * @param to
     * @param channel
     */
    @RabbitHandler
    public void releaseLockStock(Message message, StockLockedTo to, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息(被动...)");
        try {
            wareSkuService.unLockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }
    }

    @RabbitHandler
    public void orderCloseRelease(Message message, OrderTo to, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息(主动...)");
        try {
            wareSkuService.unLockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }
    }

}
